import numpy as np
import matplotlib.pyplot as plt
import cv2
#读取灰度图像
src_path=r'./img/1031/leaf/740.png'
img = cv2.imread(src_path,1)
print('img info:',src_path)
print('shape:',img.shape,' pixal num:',img.size,' dtype:',img.dtype)
zeros = np.zeros(img.shape[:2], dtype = "uint8")

#RGB拆分
b,g,r=cv2.split(img)

def get_gray_value(img,pos,harf_d):
    sum = 0
    count = 0
    start_point=[0,0]
    end_point = [0,0]
    start_point[0]=pos[0]-harf_d
    start_point[1]=pos[1]-harf_d

    end_point[0]=pos[0]+harf_d
    end_point[1]=pos[1]+harf_d
    #print(start_point[0],end_point[0])
    for i in range(start_point[0],end_point[0]+1):#行遍历
        #print(i)
        for j in range(start_point[1],end_point[1]+1):#行遍历
            #print(i,j)
            sum += img[i,j]
            count += 1
    avg=sum/count
    return img[pos[0]][pos[1]],round(avg,2)





#鼠标回调函数 
#事件 坐标 标志 返回

def show_num(event,y,x,flags,param):
    if event==cv2.EVENT_LBUTTONUP:
        #print('POS:(',x,y,') R:',r,'G:',g,'B:',b)
        #print('POS:(',x,y,')' ,img.item(x,y,0),img.item(x,y,1),img.item(x,y,2))
        print('POS:(',x,y,')' ,r[x][y])
        ave=get_gray_value(r,[x,y],5)
        print('average :(',x,y,')' ,ave)
        cv2.circle(img,(y,x),10,(0,255,0),1)
        cv2.putText(img,str(ave[1]),(y,x), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,128,0),1)
    elif event==cv2.EVENT_MBUTTONDOWN:
        print(num)
    
plt.hist(img.ravel(),256,[0,256]);
plt.show()
cv2.namedWindow('image')
#cv2.imshow('image',img)
#cv2.imshow('image',r)
#cv2.imshow('image3',(r+g)/(r-g))
#cv2.imshow('image_B',cv2.merge([b, zeros, zeros]))#带颜色的单通道灰度图
#cv2.imshow('image_G',cv2.merge([zeros, g, zeros]))#带颜色的单通道灰度图
#cv2.imshow('image_R',cv2.merge([zeros, zeros, r]))#带颜色的单通道灰度图
cv2.setMouseCallback('image',show_num)

x=615
y=758
ave=get_gray_value(r,[x,y],5)
print('WB  average :(',x,y,')' ,ave)

x=982
y=747
ave=get_gray_value(r,[x,y],5)
print('GB  average :(',x,y,')' ,ave)
while(1):
    cv2.imshow('image',img)

    key=cv2.waitKey(1)&0xFF
    if key==27:
        break
cv2.destroyAllWindows()       